package com.util.cdb.handler;

import com.util.cdb.bean.Result;
import com.util.cdb.exception.DBException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 全局异常处理
 */
@Slf4j
@RestControllerAdvice
public class DBExceptionHandler {
    @ExceptionHandler(Exception.class)
    public Result handleException(Exception ex, HttpServletRequest request, HttpServletResponse response) {
        Result result;
        if (ex instanceof DBException) {
            DBException exception = (DBException)ex;
            result = exception.getResult();
        } else {
            result = Result.resultFail(ex.getMessage());
            log.error("发生未知异常：", ex);
        }
        return result;
    }
}
